<?php
namespace app\api\controller;

use app\admin\model\Company;
use app\common\controller\Api;
use app\admin\model\Project as ProjectModel;
use app\admin\model\ProjectManager;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class Project extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取项目列表
     *
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getList()
    {
        $type = $this->request->get('type');
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $project = new ProjectModel();

        // 根据 $type 确定查询条件  -1 表示查询所有 0 表示查询进行中 1 表示已暂停 2 表示查询已完成
        $where = [];
        if ($type != -1) {
            $where['status'] = $type;
        }
        $where['company_id'] = $this->auth->id;
        // 构建查询对象
        $query = $project->with('company')->where($where);

        // 获取分页列表和总数
        $list = $query->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $list[$k]['today_counts'] = 0;
            $list[$k]['today_cars'] = 0;
            $list[$k]['total_counts'] = 0;
            $list[$k]['join_counts'] = 0;
        }
        $count = $query->where($where)->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('', $data);
    }

    /**
     * 创建项目
     *
     * @return void
     */
    public function createProject()
    {
        $userInfo = $this->auth->getUserinfo();
        if ($userInfo['cate'] != 2) {
            $this->error('您不是公司用户，无法创建项目');
        }
        $post = $this->request->post();
        $project = new ProjectModel();
        $companyModel = new Company();
        $company = $companyModel->where('uid', $this->auth->id)->find();
        $data = [
            'name' => $post['name'],
            'open_time' => strtotime($post['open_time']),
            'manager_id' => $post['manager_id'],
            'shipping_address' => $post['shipping_address'],
            'landing_address' => $post['landing_address'],
            'company_id' => $company->id,
        ];
        $res = $project->save($data);
        if ($res) {
            $this->success('创建成功');
        } else {
            $this->error('创建失败');
        }
    }

    /**
     * 修改项目
     *
     * @return void
     */
    public function editProject()
    {
        $post = $this->request->post();
        $project = new ProjectModel();
        $data = [
            'name' => $post['name'],
            'open_time' => strtotime($post['open_time']),
            'manager_id' => $post['manager_id'],
            'shipping_address' => $post['shipping_address'],
            'landing_address' => $post['landing_address'],
        ];
        $res = $project->save($data, ['id' => $post['id']]);
        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 删除项目
     * @return void
     */
    public function delProject()
    {
        $id = $this->request->post('id');
        $res = (new ProjectModel())->delete($id);
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 个人中心
     *
     * @return void
     * @throws Exception
     */
    public function personCenter()
    {
        $userInfo = $this->auth->getUserinfo();
        if ($userInfo['cate'] == 2) {
            $project = new ProjectModel();
            $projectManager = new ProjectManager();
            $companyModel = new Company();
            $company = $companyModel->where('uid', $this->auth->id)->find();
            $projectCount = $project->where('company_id', $company->id)->count();
            $projectManagerCount = $projectManager->where('company_id', $this->auth->id)->count();
            $data = [
                'projectCount' => $projectCount,
                'userInfo' => $userInfo,
                'projectManagerCount' => $projectManagerCount,
                'carCount' => 0,
                'deliveryCount' => 0,
            ];
            $this->success('', $data);
        } else {
            $this->error('您不是公司用户，无法查看');
        }
    }

    /**
     * 我的项目列表
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function myProjectList()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $companyModel = new Company();
        $company = $companyModel->where('uid', $this->auth->id)->find();
        $companyId = $company->id;
        $project = new ProjectModel();
        $projectManager = new ProjectManager();
        $user = new \app\admin\model\User();
        $query = $project->where('company_id', $companyId);
        $list = $query->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $manager = $projectManager->where('project_id', $v['id'])->find();
            $user = $user->where('id', $manager['uid'])->find();
            $list[$k]['manager_name'] = $user['username'];
        }
        $count = $query->count();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        $this->success('', $data);
    }

    /**
     * 项目人员列表
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function projectManagerList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $projectManager = new ProjectManager();
        $query = $projectManager;
        $list = $query->page($page, $limit)->select();

        $userModel = new \app\admin\model\User();
        $projectModel = new ProjectModel();

        $userIds = array_column($list, 'uid');
        $projectIds = array_column($list, 'project_id');

        $users = $userModel->whereIn('id', $userIds)->select();
        $projects = $projectModel->whereIn('id', $projectIds)->select();

        $userMap = [];
        foreach ($users as $user) {
            $userMap[$user->id] = $user;
        }

        $projectMap = [];
        foreach ($projects as $project) {
            $projectMap[$project->id] = $project;
        }

        foreach ($list as $k => $v) {
            $list[$k]['user'] = $userMap[$v['uid']] ?? null;
            $list[$k]['project'] = $projectMap[$v['project_id']] ?? null;
            $list[$k]['total_counts'] = 0;
            $list[$k]['abnormal_counts'] = 0;
        }

        $count = $query->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];

        $this->success('', $data);

    }
}